#!/usr/bin/python
# -*- coding: utf-8 -*-
from datetime import timedelta

from django.http import HttpResponse, HttpResponseRedirect, Http404
from django.views.generic.base import TemplateView
from django.shortcuts import render_to_response, render, redirect,\
    get_object_or_404
from django.contrib.admin.views.decorators import staff_member_required
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.models import Group
from django.contrib.auth.decorators import login_required, permission_required
from django.utils import simplejson as json
from django.db.models import Q

from basic.models import LibraryUser, LibraryStaff, Item, Order
from basic.forms import *


def orderView(request):
    if not (request.method == 'POST' and request.is_ajax()):
        return HttpResponse(status=405)

    if request.user.is_authenticated():
        u = request.user.get_profile()
    else:
        return HttpResponse('login first', status=404)
    try:
        item_pk = int(request.POST.get('value', -1))
    except ValueError:
        item_pk = -1
    if u.order_set.filter(item__pk=item_pk):
        return HttpResponse('already ordered', status=404)

    try:
        item = get_object_or_404(Item, pk=item_pk)
    except Http404:
        return HttpResponse('no item', status=404)
    if item.is_available:
        available = True if item.is_digital else False
        item.is_available = available
        item.save()
        u.order_set.create(library_user=u, item=item, is_ready=available)
        return HttpResponse('ok', status=200)
    else:
        return HttpResponse('already ordered', status=404)


@login_required
def orderedView(request):
    u = request.user.get_profile()
    orders = u.order_set.all()
    history = u.history_set.all()
    return render(request, 'order_list.html', {
        'orders': orders,
        'history': history,
    })


@permission_required('basic.LibraryStaff', raise_exception=True)
@staff_member_required
def changeOrder(request):
    if request.is_ajax() and request.method == 'POST':
        try:
            task = request.POST['type']
            order_id = int(request.POST['value'])
        except (KeyError, ValueError):
            return HttpResponse(status=400)
        try:
            order = get_object_or_404(Order, pk=order_id)
            item = get_object_or_404(Item, pk=order.item_id)
        except Http404:
            return HttpResponse(status=404)
        if task == 'prelong':
            order.due_date += timedelta(days=14)
            order.save()
        elif task == 'back':
            item.is_available = True
            item.save()
            order.delete()
        else:
            return HttpResponse(status=400)
        return HttpResponse(status=200)
    users = []
    for u in LibraryUser.objects.all():
        if u.order_set.count() > 0:
            users.append(u)
    return render(request, 'change_order.html', {
        'users': users,
    })


def queryView(request):
    if request.method == 'POST':
        return HttpResponse(status=400)

    query = request.GET.get('query', '')
    media = request.GET.get('media', 'all')
    search_phrases = query.split(' ')

    q_media = Q()
    q_query = Q()
    q_orders = Q()

    sl = {"dvd": "DV",
          "paper": "PA",
          "vinyl": "VI",
          "cd": "CD",
          "digital": "DI",
    }

    if media != 'all':
        q_media = Q(media__name=sl[media])

    for phrase in search_phrases:
        q_query = q_query | Q(title__icontains=phrase) | \
            Q(author__name__icontains=phrase) | \
            Q(author__surname__icontains=phrase)

    if request.user.is_authenticated():
        lib_user = request.user.get_profile()
        orders = lib_user.order_set.all()
        for order in orders:
            q_orders = q_orders | Q(id=order.item_id)

    items = Item.objects.filter(q_media & q_query & ~q_orders)

    #generowanie polecanych
    items_ref = Item.objects.filter(q_media)
    items_ref = items_ref[0:4]
    return render(request, 'query.html', {
        'items': items,
        'items_ref': items_ref,
        'signup_form':  SignupForm(),
        'login_form': LoginForm(),
    })


def loginView(request):
    next_url = request.GET.get('next', '/')
    form_action = '/login/?next=' + next_url

    if request.method == 'POST':
        form = LoginForm(request.POST, error_class=BootstrapErrorList)

        if form.is_valid():
            password = form.cleaned_data['password']
            user_login = form.cleaned_data['login']

            user = authenticate(username=user_login, password=password)
            login(request, user)
            return HttpResponse('ok') if request.is_ajax() else\
                redirect(next_url)

        elif request.is_ajax():
            e = '\n'.join([e.__unicode__() for e in form.errors.itervalues()])
            return HttpResponse(e, status=401)

        return render(request, 'auth.html', {
            'form': form,
            'form_action': form_action,
            'next_url': next_url,
            'label': 'Podaj dane logowania',
            'button_label': 'Zaloguj',
        })

    elif request.user.is_authenticated():
        return redirect(next_url)

    else:
        return render(request, 'auth.html', {
            'form': LoginForm(),
            'form_action': form_action,
            'label': 'Podaj dane logowania',
            'button_label': 'Zaloguj',
        })


def logoutView(request):
    logout(request)
    next_url = request.GET.get('next', 'home')
    if next_url == '/myorders/' or '/changeorder/':
        next_url = 'home'
    return redirect(next_url)


def signupView(request):
    next_url = request.GET.get('next', '/')

    if request.method == 'POST':
        form = SignupForm(request.POST, error_class=BootstrapErrorList)
        form_action = '/signup/?next=' + next_url

        if form.is_valid():
            name = form.cleaned_data['name']
            last_name = form.cleaned_data['last_name']
            user_login = form.cleaned_data['login']
            password = form.cleaned_data['password']

            u = User.objects.create_user(user_login, user_login, password)
            l = LibraryUser.objects.create(user=u)
            u.first_name = name
            u.last_name = last_name
            u.save()

            u = authenticate(username=user_login, password=password)
            login(request, u)

            return HttpResponse('ok') if request.is_ajax() else\
                redirect(next_url)

        elif request.is_ajax():
            e = '\n'.join([e.__unicode__() for e in form.errors.itervalues()])
            return HttpResponse(e, status=401)

        return render(request, 'auth.html', {
            'form': form,
            'form_action': form_action,
            'next_url': next_url,
            'label': 'Podaj dane rejestracji',
            'button_label': 'Zarejestruj',
        })

    elif request.user.is_authenticated():
        return redirect(next_url)

    else:
        return render(request, 'auth.html', {
            'form': SignupForm(),
            'form_action': '/signup/',
            'label': 'Podaj dane rejestracji',
            'button_label': 'Zarejestruj',
        })

def staffView(request):
    next_url = '/'

    if request.method == 'POST':
        form = SignupForm(request.POST, error_class=BootstrapErrorList)
        form_action = '/staff/?next=' + next_url

        if form.is_valid():
            name = form.cleaned_data['name']
            last_name = form.cleaned_data['last_name']
            user_login = form.cleaned_data['login']
            password = form.cleaned_data['password']

            u = User.objects.create_user(user_login, user_login, password)
            l = LibraryStaff.objects.create(user=u)
            u.first_name = name
            u.last_name = last_name
            u.save()
            group = Group.objects.get(name='LibraryStaff')
            l.user.groups.add(group)
            l.save()

            u = authenticate(username=user_login, password=password)
            login(request, u)

            return HttpResponse('ok') if request.is_ajax() else\
                redirect(next_url)

        elif request.is_ajax():
            e = '\n'.join([e.__unicode__() for e in form.errors.itervalues()])
            return HttpResponse(e, status=401)

        return render(request, 'auth.html', {
            'form': form,
            'form_action': form_action,
            'next_url': next_url,
            'label': 'Podaj dane rejestracji',
            'button_label': 'Zarejestruj',
        })

    elif request.user.is_authenticated():
        return redirect(next_url)

    else:
        return render(request, 'auth.html', {
            'form': SignupForm(),
            'form_action': '/staff/',
            'label': 'Podaj dane rejestracji',
            'button_label': 'Zarejestruj',
        })

def homeView(request):
    return render(request, 'home.html', {
        'signup_form':  SignupForm(),
        'login_form': LoginForm(),
    })
